package com.one.group.admin.excel;

import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.one.group.admin.mapper.SpMeterReadingdataMapper;
import com.one.group.model.dto.SpMeterReadingdataAddDto;
import com.one.group.model.entity.ParkingSpace;
import com.one.group.service.SpMeterReadingdataService;
import lombok.extern.slf4j.Slf4j;

import java.math.BigDecimal;
import java.util.List;

@Slf4j
public class SpMeterReadingExcelDataReadListener implements ReadListener<SpMeterReadingExcelData> {


    /**
     * 每隔5条存储数据库，实际使用中可以100条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 100;

    /**
     * 缓存的数据
     */
    private List<SpMeterReadingExcelData> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
    private SpMeterReadingdataService spMeterReadingdataService;
    private SpMeterReadingdataMapper spMeterReadingdataMapper;
    public SpMeterReadingExcelDataReadListener() {
    }

    /**
     * 如果使用了spring,请使用这个构造方法。每次创建Listener的时候需要把spring管理的类传进来
     * @param spMeterReadingdataService 抄表服务
     * @param spMeterReadingdataMapper 抄表数据Mapper
     */
    public SpMeterReadingExcelDataReadListener(SpMeterReadingdataService spMeterReadingdataService, SpMeterReadingdataMapper spMeterReadingdataMapper) {
        this.spMeterReadingdataService = spMeterReadingdataService;
        this.spMeterReadingdataMapper = spMeterReadingdataMapper;
    }

    /**
     * 这个每一条数据解析都会来调用
     * @param context
     */
    @Override
    public void invoke(SpMeterReadingExcelData data, AnalysisContext context) {
        log.info("解析到一条数据:{}", data);
        cachedDataList.add(data);
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (cachedDataList.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
            cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }

    /**
     * 所有数据解析完成了 都会来调用
     * @param context
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        // 这里也要保存数据，确保最后遗留的数据也存储到数据库
        saveData();
        log.info("所有数据解析完成！");
    }

    /**
     * 加上存储数据库
     */
    private void saveData() {
        log.info("{}条数据，开始存储数据库！", cachedDataList.size());
        List<SpMeterReadingExcelData> sp = cachedDataList.stream()
                .filter(data -> !StrUtil.isEmpty(data.getBuildingName()))
                .filter(data -> !StrUtil.isEmpty(data.getBuildingTypeName()))
                .filter(data -> !StrUtil.isEmpty(data.getCellName()))
                .filter(data -> !StrUtil.isEmpty(data.getChargestandardName()))
                .filter(data -> !StrUtil.isEmpty(data.getCurrentMonth()))
                .filter(data -> !StrUtil.isEmpty(data.getEndDegree()))
                .filter(data -> !StrUtil.isEmpty(data.getHouseNum()))
                .filter(data -> !StrUtil.isEmpty(data.getMagnification()))
                .filter(data -> !StrUtil.isEmpty(data.getStartingDegree())).toList();
        try {
            for(SpMeterReadingExcelData data:sp){
                SpMeterReadingdataAddDto spMeterReadingdataAddDto = exceltoAddDto(data);
                if(!spMeterReadingdataService.addMeterReadingdata(spMeterReadingdataAddDto)){
                    log.error("数据保存失败：{}",data);
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    private SpMeterReadingdataAddDto exceltoAddDto(SpMeterReadingExcelData spMeterReadingExcelData){
        SpMeterReadingdataAddDto spMeterReadingdataAddDto = spMeterReadingdataMapper.exceltoAddDto(spMeterReadingExcelData);
        spMeterReadingdataAddDto.setCurrentMonth(Integer.parseInt(spMeterReadingExcelData.getCurrentMonth()));
        spMeterReadingdataAddDto.setEndDegree(BigDecimal.valueOf(Double.parseDouble(spMeterReadingExcelData.getEndDegree())));
        spMeterReadingdataAddDto.setStartingDegree(BigDecimal.valueOf(Double.parseDouble(spMeterReadingExcelData.getStartingDegree())));
        spMeterReadingdataAddDto.setMagnification(BigDecimal.valueOf(Double.parseDouble(spMeterReadingExcelData.getMagnification())));
        return spMeterReadingdataAddDto;
    }
}
